var submit = 2
var list2 = []
layui.use(['table', 'admin', 'ax','laydate','element'], function (callback) {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var laydate = layui.laydate;
	var element = layui.element
	
	//tab切换
	element.on('tab(doTabBrief)',function(data){
		console.log(data.index)
	})

    laydate.render({
    	elem:'#dataDt'
        	,value:new Date()
    });

    laydate.render({
    	elem:'#startTime2'
        	,value:new Date()
    });
    
    laydate.render({
    	elem:'#endTime2'
        	,value:new Date()
    });

    /**
     * 新零帮出库汇总管理
     */
    var OrderOutcountXlb = {
        tableId: "orderOutcountXlbTable"
    };

    /**
     * 出库订单预排车表管理
     */
    var OrderOutpreparePlatooncar = {
        tableId: "orderOutpreparePlatooncarTable"
    };

    /**
     * 初始化表格的列
     */
    OrderOutcountXlb.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'clientId', hide: true, title: '主键'},
            {field: '', title: '序号', type:'numbers', width: 50},
            {field: 'getUnit', title: '客户名称', width: 140, totalRowText: '合计：'},
            {field: 'totalVolume', sort: true, title: '体积', totalRow: true, event: 'checkbox'},
            {field: 'sheng', title: '省'},
            {field: 'shi', title: '市'},
            /*            {field: 'qu', title: '区'},
                        {field: 'storehouseName', title: '发货仓库名称'},
                        {field: 'createTime', title: '创建时间'},
                        {align: 'center', toolbar: '#tableBar0', title: '操作'}*/
        ]];
    };

    /**
     * 初始化表格的列
     */
    OrderOutpreparePlatooncar.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', hide: true, title: '主键'},
            {field: '', title: '序号', type:'numbers', width: 120},
            {field: 'clientName', sort: true, title: '客户名称'},
            {field: 'carrierName', sort: true, title: '承运商'},
            {field: 'carnumber', sort: true, title: '车牌号'},
            {field: 'siji', sort: true, title: '司机'},
            {field: 'sijidianhua', sort: true, title: '司机电话'},
            {field: 'stat', sort: true, title: '状态'},
            {field: 'estDeliveryDate', sort: true, title: '预计配送日期'},
            {field: 'createTime', sort: true, title: '创建时间'},
            {align: 'center', toolbar: '#tableBar', title: '操作'}
        ]];
    };

    /**
     * 点击查询按钮
     */
    OrderOutcountXlb.search = function () {
        var queryData = {};
        // queryData['storehouseName'] = $("#storehouseName").val();
        queryData['peisongTime'] = $("#dataDt").val();
        queryData['getUnit'] = $("#clientName").val();
        queryData['sheng'] = $("#sheng").val();
        queryData['shi'] = $("#shi").val();
        queryData['qu'] = $("#qu").val();
        table.reload(OrderOutcountXlb.tableId, {
            where: queryData, page: {curr: 1},
             done:function () {
            }
        });
    };

    /**
     * 点击查询按钮
     */
    OrderOutpreparePlatooncar.search = function () {
        var queryData = {};
        queryData['condition'] = $("#condition2").val();
        queryData['carrierId'] = $("#carrierId2").val();
        queryData['storeName'] = $("#storeName2").val();
        queryData['clientName'] = $("#clientName2").val();
        queryData['startTime'] = $("#startTime2").val();
        queryData['endTime'] = $("#endTime2").val();
        table.reload(OrderOutpreparePlatooncar.tableId, {
            where: queryData, page: {curr: 1},
             done:function () {
            }
        });
    };

    /**
     * 导出excel按钮
     */
    OrderOutcountXlb.exportExcel = function () {
        var checkRows = table.checkStatus(OrderOutcountXlb.tableId);
        if (checkRows.data.length === 0) {
            Feng.error("请选择要导出的数据");
        } else {
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        }
    };

    /**
     * 导出excel按钮
     */
    OrderOutpreparePlatooncar.exportExcel = function () {
        var checkRows = table.checkStatus(OrderOutpreparePlatooncar.tableId);
        if (checkRows.data.length === 0) {
            Feng.error("请选择要导出的数据");
        } else {
            table.exportFile(tableResult2.config.id, checkRows.data, 'xls');
        }
    };

    /**
     * 点击删除
     *
     * @param data 点击按钮时候的行数据
     */
    OrderOutpreparePlatooncar.onDeleteItem = function (data) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/orderOutpreparePlatooncar/delete", function (data) {
                Feng.success("删除成功!");
                table.reload(OrderOutpreparePlatooncar.tableId);
            }, function (data) {
                Feng.error("删除失败!" + data.responseJSON.message + "!");
            });
            ajax.set("id", data.id);
            ajax.start();
        };
        Feng.confirm("是否删除?", operation);
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + OrderOutcountXlb.tableId,
        url: Feng.ctxPath + '/hxOrderOutMap/listNew',
        page: true,
        limit: 240,
		limits:[60,120,240,360,480,1500,5000],
        height: "full-60",
        toolbar: '#toolbarfrom',
        totalRow: true ,//开启合计行
        cellMinWidth: 100,
        cols: OrderOutcountXlb.initColumn()
    });

    // 渲染表格
    var tableResult2 = table.render({
        elem: '#' + OrderOutpreparePlatooncar.tableId,
        url: Feng.ctxPath + '/orderOutpreparePlatooncar/list',
        page: true,
        limit: 240,
		limits:[60,120,240,360,480,1500,5000],
        height: "full-60",
        toolbar: '#toolbarfrom',
        cellMinWidth: 100,
        cols: OrderOutpreparePlatooncar.initColumn()
    });

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        OrderOutcountXlb.search();
    });

    // 搜索按钮点击事件
    $('#btnSearch2').click(function () {
        OrderOutpreparePlatooncar.search();
    });


    function addMarkerAt(lnglat, store) {
        // 创建一个新的 Marker 实例：
        const marker = new AMap.Marker({
            position: lnglat,
            title: "新位置",
            icon: "https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
            offset: new AMap.Pixel(-25, -60)
        });

        // 创建信息窗体的内容
        const content = `
            <div class="custom-info-window" style="width: 150px; background: #FFFFFF; padding: 10px;">
                <p><strong>${store.getUnit}</strong></p>
                <p>${store.shi}${store.qu}</p>
                <p>地址：<span>${store.address}</span></p>
            </div>
        `;

        var content2 = [
            `<div class="custom-info-window" style="width: 150px; background: #FFFFFF; padding: 10px; border-radius: 5%;">
                <p><strong>${store.getUnit}</strong></p>
                <p>${store.shi}${store.qu}</p>
                <p>地址：<span>${store.address}</span></p>
            </div>`
        ]


        // 创建信息窗体
        const infoWindow = new AMap.InfoWindow({
            content: content2.join("<br>"),
            isCustom: true,
            offset: new AMap.Pixel(0, -30),
            // autoPan: false
        });

        // 添加点击事件处理函数
        marker.on('click', function () {
            infoWindow.open(map, marker.getPosition());
        });

        // 将创建的点标记添加到地图上
        map.add(marker);
    }

    // 创建地理编码实例
    AMap.plugin("AMap.Geocoder", function () {
        geocoder = new AMap.Geocoder({
            radius: 1000, // 搜索半径
            extensions: "all", // 返回地址组成的所有要素
            async: false // 同步返回结果
        });
    })

    // 添加一个标志变量，用于控制中心点的设置
    let isFirstLocationSet = false;

    // 批量地图标点
    function markStoresOnMap(checkRowsData) {
        checkRowsData.forEach(function (store) {
            // 直接使用数据中的经纬度
            var lnglat = [store.longitude, store.latitude];
            addMarkerAt(lnglat,store);

            // 如果是第一次设置中心点，则设置中心点为当前门店的经纬度
            if (!isFirstLocationSet) {
                map.setZoom(8); // 设置缩放级别
                map.setCenter(lnglat); // 设置中心点为当前门店的经纬度
                isFirstLocationSet = true;
            }
        });
    }

    // 选择门店点击事件
    $('#xuanzecar').click(function () {
        var checkRows = table.checkStatus(OrderOutcountXlb.tableId);
        if (checkRows.data.length === 0){
            Feng.error("请选择要标点的门店");
        }else {
            // console.log("点击",checkRows.data);
            // 清空地图上的所有标记
            map.clearMap();
            isFirstLocationSet = false;
            // 标记选中的门店
            markStoresOnMap(checkRows.data);
        }
    });

    // 清空标点
    $('#clearMarket').click(function () {
        OrderOutcountXlb.clearMarket();
    });

    OrderOutcountXlb.clearMarket = function () {
        map.clearMap();
        map.setZoom(8); // 设置缩放级别
    };

	//选择订单明细
	table.on('checkbox(' + OrderOutcountXlb.tableId + ')', function(obj){
		if(obj.checked){
			if(obj.type == 'all'){
				var new_list = []
				var data = table.checkStatus(OrderOutcountXlb.tableId).data
				for (var i = 0; i < data.length; i++) {
					var obj = {}
					obj.idi = data[i].id
					obj.volume = data[i].volume
					obj.matrixingNumber = data[i].matrixingNumber
					new_list.push(obj)
				}
				list2 = new_list
				sumVolume()
			} else if (obj.type == 'one'){
				var new_list = []
				var data = obj.data
				for (var i = 0; i < list2.length; i++) {
					if(data.id != list2[i].id){
						new_list.push(list2[i])
					}
				}
				var obj = {}
				obj.idi = data.id
				obj.volume = data.volume
				obj.matrixingNumber = data.matrixingNumber
				new_list.push(obj)
				list2 = new_list
				sumVolume()
			}
		} else {
			if(obj.type == 'all'){
				list2 = []
				$("#volume").text("0")
				$("#matrixingNumber").text("0")
			} else if (obj.type == 'one'){
				var new_list = []
				var data = obj.data
				for (var i = 0; i < list2.length; i++) {
					if(data.clientId != list2[i].id){
						new_list.push(list2[i])
					}
				}
				list2 = new_list
				sumVolume()
			}
		}
	 });

    // 工具条点击事件
    table.on('tool(' + OrderOutcountXlb.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
		if(layEvent === 'checkbox'){
		　　var flag = !obj.tr.find(':checkbox:first').prop('checked');
		　　obj.tr.find(':checkbox').prop('checked',flag);
		　　if(flag){
		　　　　	obj.tr.find('.layui-form-checkbox').addClass('layui-form-checked');
				data.checked = true
				obj.update(data)//更新编辑行
				
				var new_list = []
				for (var i = 0; i < list2.length; i++) {
					if(data.clientId != list2[i].id){
						new_list.push(list2[i])
					}
				}
				var obj = {}
				obj.idi = data.id
				obj.volume = data.volume
				obj.matrixingNumber = data.matrixingNumber
				new_list.push(obj)
				list2 = new_list
				sumVolume()
		　　}  else {
		　　　　	obj.tr.find('.layui-form-checkbox').removeClass('layui-form-checked');
				data.checked = false
				obj.update(data)//更新编辑行
				
				var new_list = []
				for (var i = 0; i < list2.length; i++) {
					if(data.clientId != list2[i].idi){
						new_list.push(list2[i])
					}
				}
				list2 = new_list
				sumVolume()
		　　}
		}else if(layEvent === 'editDetailed'){
            submit = 2
            layer.open({
                type: 2,
                title: '拆体积',
                area: ['750px', '550px'],
                anim: 5,
                content: Feng.ctxPath + '/orderOutcountXlb/toctj?id=' + data.id,
                end: function () {
                    if(submit == 1){
                        table.reload(OrderOutcountXlb.tableId);
                    }
                }
            });
        }
    });

	function sumVolume(){
		let volume = 0
		let matrixingNumber = 0
		for (var i = 0; i < list2.length; i++) {
			volume += list2[i].volume*1
			matrixingNumber += list2[i].matrixingNumber*1
		}
		$("#volume").text(volume.toFixed(4))
		$("#matrixingNumber").text(matrixingNumber.toFixed(3))
	}

    // 导出excel
    $('#btnExp').click(function () {
        OrderOutcountXlb.exportExcel();
    });

    // 导出excel
    $('#btnExp2').click(function () {
        OrderOutpreparePlatooncar.exportExcel();
    });

    // 工具条点击事件
    table.on('tool(' + OrderOutpreparePlatooncar.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'delete') {
            OrderOutpreparePlatooncar.onDeleteItem(data);
        }
    });

});
